const http=require('http');
const fs=require('fs');
const url=require('url');
const path=require('path');

const server=http.createServer((request,response)=>{

    //读取文件
   //动态获取网站url
    let {pathname}=new URL(request.url,'http://127.0.0.1');
    //根目录
    let root=__dirname+'/界面';//可自己设置
    // let root=__dirname+'/../'
    let filepath=root+pathname;
    let mines={
        html:'text/html',
        css:'text/css',
        js:'text/javascript',
        png:'image/png',
        jpg:'image/jpeg',
        gif:'image/gif',
        mp4:'vedio/mp4',
        mp3:'audio/mp3',
        json:'application/json'
    }

    let ext=path.extname(filepath).slice(1);//通过路径判断是什么类型
    console.log(ext);
    fs.readFile(filepath,(err,data)=>{
        if(err)
        {  response.setHeader('content-type','text/html;charset=utf-8');
            response.statusCode=500;
            response.end('出错了');
            return;
        }
        let type=mines[ext];
        //判断是type的什么类型
        if(type)
        {
            response.setHeader('content-type',type+';charset=utf-8');
        } 
        else
        {
            response.setHeader('content-type','appplication/octet-stream')
        }
        if(ext =='html')//一般网页会根据网页编码进行
        {
            response.setHeader('content-type',type+';charset=utf-8');
        }
        else{
            response.setHeader('content-type',type);
        }
       
        
            response.end(data);
    });
   
    // if(pathname ==='/')
    // {   let html=fs.readFileSync('../界面/主页.html');
    //      response.end(html);
    // }
    // else if(pathname ==='index.css')
    // {    let css=fs.readFileSync(__dirname+'../界面/css/index.css');
    //     response.end(html);
    // }
    // else if(pathname==='play.js')
    // {
    //     let js=fs.readFileSync(__dirname+'../界面/js/play.js');
    //     response.end(js);

    // }
    // else{
    //     response.statusCode=404;
    //     response.end('出错了');
    // }
   
});

server.listen(8000,()=>{

    console.log('服务启动成功');
});